#pragma once
#include<sys/types.h>
#include<sys/ipc.h>
#include<string.h>
#include"log.hpp"
#include<sys/shm.h>
#include<unistd.h>
#include<sys/stat.h>

#define MEMSIZE 4096


const char* pathname = "/home/wjb";
int porj_id = 04444;

Log log;


int getKey()
{
    key_t k = ftok(pathname,porj_id);
    if(k < 0)
    {
        log(Error,"Get Key Fail!!!");
        exit(1);
    }

    return k;
}



int getSharedMemoryHelper(int flag)
{
    key_t k = getKey();

    int shmid = shmget(k,MEMSIZE,flag);
    if(shmid < 0)
    {
        log(Error,"Get ShareMemory Fail!!!");
        exit(1);
    }

    return shmid;
}


int createSharedMem()
{
    int shmid = getSharedMemoryHelper(IPC_CREAT | IPC_EXCL | 0666);
    if(shmid < 0)
    {
        log(Fatal,"Create Fail!!");
        exit(1);
    }
    return shmid;
}

int getSharedMem()
{
    int shmid = getSharedMemoryHelper(IPC_CREAT);
    if(shmid < 0)
    {
        log(Fatal,"Get Fail!!");
        exit(1);
    }
    return shmid;
}





#define FIFO_FILE "myfifo"
#define MODE 0666


enum
{
    FILE_CREATE_ERR = 1,
    FILE_DELETE_ERR,
    FILE_OPEN_ERR
};


class Init
{
public:
    Init()
    {
        int n = mkfifo(FIFO_FILE,MODE);
        if(n == -1)
        {
            perror("mkfifo");
            exit(FILE_CREATE_ERR);
        }
    }

    ~Init()
    {
        int n = unlink(FIFO_FILE);
        if(n == -1)
        {
            perror("unlink");
            exit(FILE_DELETE_ERR);
        }
    }

};